package plugins;

import play.Logger;
import play.Play;
import play.PlayPlugin;
import play.libs.Crypto;
import play.mvc.Http;
import play.mvc.Router;

import java.io.PrintStream;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Set;

/**
 * @author zhangzc
 * @since 2017/7/6
 */
public class XPlayPlugin extends PlayPlugin {

    @Override
    public void onConfigurationRead() {
        super.onLoad();
        printConfiguration();
        printRoutes();
    }

    private void printRoutes() {
        StringBuilder print = new StringBuilder("-- Routes:S --\n");
        for(Router.Route r: Router.routes){
            print.append(r.routesFile == null ? "[Play]": r.routesFile);
            print.append("\t");
            print.append(r.path);
            print.append("\t");
            print.append(r.action);
            print.append("\n");
        }
        print.append("-- Routes:E --\n");
        Logger.info(print.toString());
    }

    void printConfiguration() {
        StringBuilder print = new StringBuilder("-- listing properties:S --\n");
        Hashtable<String, Object> h = new Hashtable<>();
        Enumeration<Object> enumeration = Play.configuration.keys();
        while (enumeration.hasMoreElements()) {
            Object s = enumeration.nextElement();
            String key = s.toString();
            String val = Play.configuration.getProperty(key);
            if (val.length() > 60) {
                val = val.substring(0, 57) + "...";
            }
            print.append(key + "=" + val).append('\n');
        }


        print.append("-- listing properties:E --\n");
        Logger.info(print.toString());
    }

    @Override
    public boolean rawInvocation(Http.Request request, Http.Response response) throws Exception {
        if (request.path.equals("/EnvHealth.html")) {
            if(!Play.started) {
                response.print("Application is not started");
                response.status = 503;
                return true;
            }
            response.contentType = "text/plain";

            response.status = 200;
            response.print("OK");
            return true;
        }
        return super.rawInvocation(request, response);
    }
}
